<?php

namespace app\admin\controller\coupon;

use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 优惠券
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    /**
     * Coupon模型对象
     * @var \app\admin\model\coupon\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\coupon\Coupon;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
//        if(!$params){
//            $this->error('提交错误');
//        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $money =$params['money'];
        $title= $params['title'];
        $describe= $params['describe'];
        $term= $params['term'];
        $status= $params['status'];
        $end_time= $params['end_time'];
        $data=[
            'title'=>$title,
            'money'=>$money,
            'describe'=>$describe,
            'term'=>$term,
            'status'=>$status,
            'end_time'=>$end_time,
        ];
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->create($data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 发放优惠券
     */
    public function send(){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $coupon=$this->model::get(['id'=>$params['id']??0])?:[];
            if(!$coupon){
                $this->error('优惠券信息不存在');
            }

            if($params['type']=='all'){
                $ids=User::where(['status'=>'normal'])->column('id')?:[];
            }
            else{
                $id_arr=explode(',',$params['uid']);
                if(!$id_arr){
                    $this->error('请选择至少一个用户作为发放对象');
                }

                $ids=User::where(['status'=>'normal','id'=>['in',$id_arr]])->column('id')?:[];
                if(!$ids){
                    $this->error('请选择有效用户');
                }
            }
            $insert_data=[];
            foreach ($ids as $i){
                $insert_data[]=[
                    'uid'=>$i,
                    'coupon_id'=>$params['id'],
                    'get_time'=>time(),
                    'expiration_time'=>$coupon->end_time,
                    'status'=>1,
                    'createtime'=>time()
                ];
            }
          \app\admin\model\coupon\UseCoupon::insertAll($insert_data);
            $this->success('成功');
        }
        $id=request()->param('id');
        if(!$id){
            $this->error('缺少优惠券id');
        }
        $this->view->assign("id", $id);
        return $this->view->fetch();
    }

}
